package com.twu.biblioteca.options;


import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.twu.biblioteca.Application;
import com.twu.biblioteca.Book;
import com.twu.biblioteca.Interfaces.MenuOption;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class ReserveBookOption implements MenuOption {
    @Override
    public void run(Application application) {

        new ListAllBooksOption().run(application);

        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufRead = new BufferedReader(inputStreamReader);
        Boolean reservingBook = true;
        while (reservingBook) {
            try {
                System.out.println("Enter the book number to select it: press 0 to go back");
                String textInput = bufRead.readLine();
                final int IntegerChoice = Integer.parseInt(textInput);
                reserveBook(application.getBooks(), IntegerChoice);
                if (IntegerChoice == 0) {
                    reservingBook = false;
                }


            } catch (IOException err) {

            }
        }
    }

    public void reserveBook(List<Book> books, int integerChoice) {
        Iterable<Book> filtered = filterBooks(books, integerChoice);

        for (Book book : filtered) {
            if (book.isAvailable()) {
                book.take();
                System.out.println("You have reserved " + book);
                System.out.println("Thank You! Enjoy the book.");
            }
        }
        if (filtered == null) {
            System.out.println("Sorry we don't have that book yet.");

        }
    }

    public Iterable<Book> filterBooks(List<Book> books, final int integerChoice) {
        Predicate<Book> filter = new Predicate<Book>() {
            @Override
            public boolean apply(Book input) {
                return input.getId() == integerChoice;
            }
        };
        return Iterables.filter(books, filter);
    }
}
